package controller

import (
	"errors"
	"ginfast/api/system/dto"
	"ginfast/api/system/model"
	"ginfast/pkg/dao"
	"ginfast/pkg/gctx"
	"ginfast/pkg/tree"

	"github.com/gin-gonic/gin"
)

// Dept 部门
type Dept struct {
}

// ListHandler 列表
func (Dept) ListHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	var data []model.SysDept
	p.DbModelWhere(&model.SysDept{}).Find(&data)
	gctx.JSONWriteData(data, c)
}

// ListExcludeHandler 部门列表（排除节点）
func (Dept) ListExcludeHandler(c *gin.Context) {
	// id, err := gctxQueryInt(c, "id")
	// if err != nil {
	// 	JSONP(StatusError).WriteTo(c)
	// }
	// where := fmt.Sprintf("id != %d", id)
	// var depts []model.Dept
	// dao.DbFindAll(where, depts, "order_num asc")
	gctx.JSONOK(c)
}

// GetHandler 查询部门详细
func (Dept) GetHandler(c *gin.Context) {
	dao.QueryByID(&model.SysDept{}, c)
}

// TreeSelectHandler 查询下拉树结构
func (Dept) TreeSelectHandler(c *gin.Context) {
	var nodes []tree.Node
	if err := dao.DB().Model(&model.SysDept{}).Scan(&nodes).Error; err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	data := tree.Build(nodes)
	gctx.JSONWriteData(data, c)
}

// RoleDeptTreeSelectHandler 根据角色ID查询树结构
func (Dept) RoleDeptTreeSelectHandler(c *gin.Context) {
	gctx.JSONOK(c)
}

func checkAddDept(s *model.SysDept) error {
	if err := dao.DbFirstBy(&model.SysDept{}, "name like ?", s.Name); err != nil {
		return err
	}
	return nil
}

// AddHandler 新增
func (Dept) AddHandler(c *gin.Context) {
	var p model.SysDept
	//获取参数p
	if err := c.ShouldBind(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if err := checkAddDept(&p); err == nil {
		gctx.JSONWriteError(errors.New("dept already exists"), c)
		return
	}
	if err := dao.DbCreate(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

// UpdateHandler 修改
func (Dept) UpdateHandler(c *gin.Context) {
	var p model.SysDept
	if err := c.ShouldBind(&p.SysDeptOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if err := dao.DbUpdateModel(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

// DeleteHandler 删除
func (Dept) DeleteHandler(c *gin.Context) {
	dao.Deletes(&model.SysDept{}, c)
}

func (o Dept) Router(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/list/exclude/:id", o.ListExcludeHandler)
	r.GET("/:id", o.GetHandler)
	r.GET("/treeSelect", o.TreeSelectHandler)
	r.GET("/roleDeptTreeselect/:id", o.RoleDeptTreeSelectHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.DELETE("/:id", o.DeleteHandler)
}
